<template>
  <div class="page-list" v-loading.fullscreen.lock="loadingListData">
    <div ref="tableHeaderContainer">
      <list-search
        :placeholder="placeholder"
        :config="{ fields: this.partFields }"
        :options="options"
        @search="search"
        @reset="reset"
        @updateCreateTime="updateCreateTime"
      >
        <div class="bill-date">
          <el-date-picker
            v-model="options.createTime"
            type="daterange"
            unlink-panels
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :picker-options="options.pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            value-format="timestamp"
          >
          </el-date-picker>
        </div>
      </list-search>
    </div>

    <div ref="tableDoContainer" class="page-list-section">
      <div class="operation-bar-container bill-bar-container">
        <div class="action-button-group">
          <el-dropdown trigger="click" v-if="isButtonDisplayed">
            <span
              class="el-dropdown-link el-dropdown-btn"
              @click="trackEventHandler()"
            >
              {{$t('common.base.moreOperator')}}
              <i class="iconfont icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportData(false)">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportData(true)">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span
            class="el-dropdown-link el-dropdown-btn"
            @click="showAdvancedSetting"
            >{{$t('common.base.choiceCol')}} <i class="iconfont icon-more"></i
          ></span>
        </div>
      </div>
    </div>

    <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
      <base-selection-bar ref="baseSelectionBar" v-model="multipleSelection.list" @toggle-selection="toggleSelection" @show-panel="() => multipleSelection.multipleSelectionPanelShow = true" />
    </div> -->

    <div class="bg-w bor-ra-4 pad-l-10 pad-r-10">
      <el-table
        v-table-style
        stripe
        ref="table"
        :data="page.list"
        :border="true"
        @selection-change="select"
        @sort-change="sort"
        @header-dragend="headerDragend"
        class="bbx-normal-list-box"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData
            v-show="!loadingListData"
            :notice-msg="$t('common.base.tip.noData')"
          ></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          width="48"
          class-name="select-column"
          align="center"
        >
        </el-table-column>

        <el-table-column
          v-for="(column, index) in columns"
          :key="`${column.field}_${index}`"
          v-if="column.show"
          :label="column.label"
          :width="column.width || '120px'"
          :prop="column.field"
          :sortable="column.sortable"
          :fixed="column.fixLeft || column.fixed || false"
          :class-name="
            column.field == 'taskNo' ? 'page-name-superscript-td' : ''
          "
          :show-overflow-tooltip="column.tooltip && column.field !== 'taskNo'"
        >
          <template slot-scope="scope" style="position: relative">
            <template v-if="column.field == 'taskNo'">
              <a
                :href="`${$resourcePrefix}/partV2/category/detail?id=${scope.row.id}`"
                class="view-detail-btn"
                @click.prevent="openDetail(scope.row)"
              >
                {{ scope.row.taskNo }}
              </a>
            </template>

            <template v-else-if="column.field == 'businessLabel'">
              <span
                class="view-detail-btn table-whitelist"
                @click.prevent="openDetailTab(scope.row)"
              >
                {{ scope.row.businessLabel }}
              </span>
            </template>

            <template v-else-if="column.field === 'createTime'">
              {{ scope.row.createTime | fmt_datetime }}
            </template>

            <template v-else-if="column.field === 'payTime'">
              {{ scope.row.payTime | fmt_datetime }}
            </template>

            <template v-else-if="column.field === 'tradeResult'">
              {{ formatTradeResult(scope.row.tradeResult) }}
            </template>

            <template v-else-if="column.field === 'operate'">
              <!-- 待支付 -->
              <template
                v-if="
                  (scope.row.tradeResult == 1 || scope.row.tradeResult == 2) &&
                  scope.row.tradeType == 3
                "
              >
                <div class="link-text" @click="confirmPay(scope.row)">
                  {{$t('bill.list.confirmPay')}}
                </div>
              </template>
            </template>

            <template v-else>
              {{ scope.row[column.field] }}
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div ref="tableFooterContainer" class="bbx-normal-table-footer-10">
        <table-footer
          :page="page"
          :multiple-selection="multipleSelection"
          @search="search"
          @toggleRowSelection="toggleRowSelection"
          @clearSelection="clearSelection"
        ></table-footer>
      </div>

      <!-- v-if="allowImportAndExport" -->
      <base-export
        ref="exportPanel"
        :columns="filterColumns"
        :build-params="buildExportParams"
        :validate="checkExportCount"
        method="get"
        :download-url="billListExport_2"
        :action="billListExport"
      ></base-export>

      <biz-select-column
        ref="advanced"
        mode="paymentBillOnline"
        @save="saveColumnStatus"
      />
    </div>
  </div>
</template>

<script>
// pageDes 在线支付管理
import _ from 'lodash';
import Page from '@src/model/Page';
import AuthUtil from '@src/util/auth';
import { storageSet, storageGet } from '@src/util/storageV2';
import { checkButtonDisplayed } from '@src/util/dom';

import ListSearch from './components/ListSearch';
import TableFooter from './components/TableFooter';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
/* export & import */
import { billListExport, billListExport_2 } from '@src/api/Export';
/* api */
import { confirmPay } from '@src/api/SettingApi.ts';
/* util */
import {
  openTabForTaskView,
  openTabPaasJiXiu,
} from '@src/util/business/openTab';
import qs from 'qs';
import { safeNewDate } from '@src/util/time';
import { tableFields } from './field.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { formatDate, hyphenate, objectDateToTimestamp } from 'pub-bbx-utils'
import { t } from '@src/locales';

const STORAGE_COLNUM_KEY = 'bill_list_column';
const STORAGE_PAGESIZE_KEY = 'bill_list_pagesize';
const tradeResultMap = {
  1: t('bill.list.tradeResultMap[0]'),
  2: t('bill.list.tradeResultMap[0]'),
  3: t('bill.list.tradeResultMap[1]'),
  4: t('bill.list.tradeResultMap[2]'),
  5: t('bill.list.tradeResultMap[3]'),
  6: t('bill.list.tradeResultMap[4]'),
  7: t('bill.list.tradeResultMap[5]'),
  8: t('bill.list.tradeResultMap[6]'),
};

export default {
  name: 'bill-list',
  mixins: [ThemeMixin],
  data() {
    let pageSize = storageGet(STORAGE_PAGESIZE_KEY) || 10;
    let originModel = {
      keyword: '', // 关键字
      pageNum: 1,
      pageSize,
      sortBy: {},
    };

    return {
      isButtonDisplayed: checkButtonDisplayed(),
      placeholder: t('bill.list.searchPlaceholder'),
      multipleSelection: {
        leftName: t('bill.list.payee'),
        rightName: t('bill.list.budget'),
        list: [],
        multipleSelectionPanelShow: false,
      },

      auths: {}, // 权限对象

      columns: [],
      isExpand: false,
      pending: false,

      originModel,
      model: _.assign({}, originModel),

      page: new Page(),
      selected: [],
      loadingListData: false,
      options: {
        pickerOptions: {
          shortcuts: [
            {
              text: t('common.base.aboutTime.today2'),
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                picker.$emit('pick', [start, end]);
              },
            },
            {
              text: t('common.base.aboutTime.yesterday2'),
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
                picker.$emit('pick', [start, end]);
              },
            },
            {
              text: t('common.base.aboutTime.lastDays', {data1: 7}),
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              },
            },
            {
              text: t('common.base.aboutTime.lastDays', {data1: 30}),
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              },
            },
          ],
        },
        createTime: [],
        amount: {
          amountStart: '',
          amountEnd: '',
        },
      },
      selectedLimit: 200,
      billListExport,
      billListExport_2,
      tableContainerHeight: '440px',
      tableKey: (Math.random() * 1000) >> 2,
      selectColumnState: 'paymentBull_list_select',
    };
  },
  computed: {
    partFields() {
      let fixedFields = [
        {
          displayName: t('bill.list.displayName.userName'),
          fieldName: 'userName',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.orderNo'),
          fieldName: 'orderNo',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.businessLabel'),
          fieldName: 'businessLabel',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.thirdOrderNo'),
          fieldName: 'thirdOrderNo',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.createTime'),
          fieldName: 'createTime',
          formType: 'datetime',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          operator: 'between',
          orderId: 99,
        },
        {
          displayName: t('bill.list.displayName.payTime'),
          fieldName: 'payTime',
          formType: 'datetime',
          isExport: false,
          isNull: 1,
          isSystem: 1,
          operator: 'between',
          orderId: 99,
        },
        {
          displayName: t('bill.list.displayName.buyLogonId'),
          fieldName: 'buyLogonId',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.sellerLogonId'),
          fieldName: 'sellerLogonId',
          formType: 'text',
          isExport: false,
          isSystem: 1,
        },
        {
          displayName: t('bill.list.displayName.amountRange'),
          fieldName: 'amountRange',
          formType: 'range',
          isExport: false,
          isSystem: 1,
          components: 'bill-amount-range',
        },
      ];

      return fixedFields
        .filter(f => f.formType !== 'separator' && f.formType !== 'info')
        .map(f => {
          // 调整字段顺序
          if (f.fieldName === 'partType') {
            f.orderId = 1;
            f.show = true;
          }

          if (f.fieldName === 'partName') {
            f.orderId = 0;
            f.show = true;
          }

          return f;
        })
        .sort(a => a.orderId);
    },

    // 是否允许导入导出
    allowImportAndExport(){
      return true
      // return AuthUtil.hasAuth(this.auths, 'EXPORT_IN')
    },
    // 是否有编辑权限
    allowEdit() {
      // return true;
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EDIT');
    },
    allowInout() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_INOUT');
    },
    filterColumns() {
      return this.columns
        .filter(c => c.label)
        .filter(c => c.field !== 'operate');
    },
  },
  methods: {
    formatTradeResult(tradeResult) {
      return tradeResultMap[tradeResult] || '';
    },
    async confirmPay(row) {
      try {
        const confirm = await this.$confirm(
          t('bill.list.tip.confirmPay'),
          t('common.base.toast'),
          {
            confirmButtonText: t('common.base.confirm'),
            cancelButtonText: t('common.base.cancel'),
            type: 'warning',
          }
        );
        if (!confirm) return;

        this.loadingListData = true;

        const params = {
          orderNo: row.orderNo,
        };

        confirmPay(params).then(result => {
          const isSuccess = result.success || result.succ;

          if (isSuccess) {
            this.$message.success(t('common.base.tip.operationSuccess'));
            this.model.pageSize = 10;
            this.model.pageNum = 1;
            this.loadData();
          } else {
            this.$message.error(result.message);
            this.loadingListData = false;
          }
        });
      } catch (error) {
        console.warn(error);
      }
    },
    // 表格底部组件
    toggleRowSelection(row) {
      this.$refs.table.toggleRowSelection(row);
    },

    clearSelection() {
      this.$refs.table.clearSelection();
    },

    buildExportParams(checkedArr, ids) {
      let exportAll = !ids || !ids.length;
      let exportSearchModel = exportAll
        ? {
            ...this.buildParams(),
            exportTotal: this.page.total,
          }
        : {
            ...this.buildParams(),
            exportTotal: ids.length,
          };
      return {
        checked: checkedArr.join(','),
        idList: exportAll ? [] : ids,
        ...exportSearchModel,
      };
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || !ids.length;
      return exportAll && this.page.total > max
        ? t('common.base.tip.exportMostTip')
        : null;
    },

    // 选择列
    showAdvancedSetting() {
      // window.TDAPP.onEvent('pc：在线支付管理-选择列事件');
      console.log(this.columns, 'columns');
      this.$refs.advanced.open(this.columns);
    },
    getLocalStorageData() {
      const dataStr = storageGet(STORAGE_COLNUM_KEY) || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(STORAGE_COLNUM_KEY, JSON.stringify(data));
    },

    // 导出支付记录
    exportData(exportAll) {
      // if(!this.allowImportAndExport || !this.allowEdit || !this.allowInout) return;
      let ids = [];
      let fileName = t('bill.list.exportFileName', {date: formatDate(safeNewDate(), 'YYYY-MM-DD')});
      if (!exportAll) {
        if (!this.selected.length)
          return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.selected.map(item => item.id);
      }
      this.$refs.exportPanel.open(ids, fileName, true);
    },

    importSucc() {
      this.loadData();
    },
    openDetail(row) {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.taskId,
        titleKey: row.taskId,
        fromId
      })
    },
    openDetailTab(row) {
      // businessType 1工单 2寄修 3商城 design by 既此
      if (row.businessType == 3) {
        let fromId = window.frameElement.getAttribute('id');
        openAccurateTab({
          type: PageRoutesTypeEnum.PageOrderDetailV2,
          key: row.businessNo,
          params: `id=${row.businessNo}`,
          fromId,
        });
      }else if (row.businessType == 1) {
        openTabForTaskView(row.businessNo);
      }else if (row.businessType == 2) {
        const businessCallbackUrl = row?.businessCallback || '';
        const params = qs.parse(businessCallbackUrl);
        const { formId, formContentId, processId } = params;

        if (formId && formContentId && processId) {
          openTabPaasJiXiu(formId, formContentId, processId, row.businessLabel);
        }
      }
    },
    // 计算已选择
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.list.filter(ms =>
        this.page.list.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    select(data) {
      let tv = this.selectionCompute(data);

      let original = this.multipleSelection.list.filter(ms =>
        this.page.list.some(cs => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
                this.$refs.table.toggleRowSelection(row, false);
              })
            : this.$refs.table.clearSelection();
        });
        return this.$platform.alert(t('common.base.tip.choiceLimit', {limit: this.selectedLimit}));
      }

      this.multipleSelection.list = [];
      this.selected = tv;
      tv.forEach(item => {
        item.serialNumber = item.userName;
        item.name = item.totalAmount.toFixed(2);
        this.multipleSelection.list.push(item);
      });
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    // 匹配选中的列
    matchSelected() {
      if (!this.multipleSelection.list.length) return;

      const selected =
        this.page.list.filter(c => {
          if (this.multipleSelection.list.some(sc => sc.id === c.id)) {
            this.multipleSelection.list = this.multipleSelection.list.filter(
              sc => sc.id !== c.id
            );
            this.multipleSelection.list.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },

    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows && rows.length <= 0) this.$refs.table.clearSelection();

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.clearSelection();
        this.multipleSelection.list = [];
      }
    },

    jump(pageNum) {
      this.model.pageNum = pageNum;
      this.loadData();
    },

    pageSizeChange(pageSize) {
      this.model.pageSize = pageSize;
      this.originModel.pageSize = pageSize;

      this.loadData();

      // 存入localStorage
      storageSet(STORAGE_PAGESIZE_KEY, pageSize);
    },

    search(data, type) {
      this.trackEventHandler('search');
      this.visible = false;
      if (type == 'jump') {
        this.jump(data.pageNum);
        return;
      }
      if (type == 'pageSizeChange') {
        this.pageSizeChange(data.pageSize);
        return;
      }
      this.buildModel(data);
      this.loadData();
    },

    buildModel(data) {
      this.model = _.assign({}, this.originModel);
      this.$refs.table.clearSort();

      this.model.keyword = data.keyword;

      this.buildTime(this.options.createTime);

      if (!data.moreConditions || !data.moreConditions.fields) return;

      let fields = data.moreConditions.fields;
      let form = data.moreConditions.form;

      let tv = null;
      let fn = '';

      for (let i = 0; i < fields.length; i++) {
        tv = fields[i];
        fn = tv.fieldName;

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        if (tv.fieldName === 'userName') {
          this.model.userName = form[fn];
          continue;
        }

        if (tv.fieldName === 'orderNo') {
          this.model.orderNo = form[fn];
          continue;
        }

        if (tv.fieldName === 'businessLabel') {
          this.model.businessLabel = form[fn];
          continue;
        }

        if (tv.fieldName === 'thirdOrderNo') {
          this.model.thirdOrderNo = form[fn];
          continue;
        }

        if (tv.fieldName === 'payTime') {
          // 交易付款时间
          this.model.payTimeStart = form[fn][0];
          this.model.payTimeEnd = form[fn][1];
          continue;
        }

        if (tv.fieldName === 'buyLogonId') {
          this.model.buyLogonId = form[fn];
          continue;
        }

        if (tv.fieldName === 'sellerLogonId') {
          this.model.sellerLogonId = form[fn];
          continue;
        }

        if (tv.fieldName === 'amountRange') {
          // this.model.receiptAmountMin = form[fn].amountStart;
          // this.model.receiptAmountMax = form[fn].amountEnd;
          this.model.totalAmountMin = form[fn].amountStart;
          this.model.totalAmountMax = form[fn].amountEnd;
          this.options.mounted = form[fn];
          continue;
        }
      }
    },

    reset() {
      this.trackEventHandler('reset');
      this.visible = false;
      this.model = _.assign({}, this.originModel);
      this.options.createTime = [];
      this.options.amount.amountStart = '';
      this.options.amount.amountEnd = '';
      this.$refs.table.clearSort();
      this.loadData();
    },

    sort({ column, prop, order }) {
      let sortBy = {};

      if (prop && order) {
        // let tableName = 'pbo';
        // let key = `${tableName}.${prop}`
        let key = hyphenate(`${prop}`);
        sortBy[key] = order == 'ascending';
      }

      this.model.sortBy = sortBy;
      this.loadData();
    },

    async loadData() {
      this.loadingListData = true;
      try {
        let res = await this.fetchData();
        if (res.success == false) {
          this.loadingListData = false;
          this.$platform.notification({
            title: res.message,
            type: 'error',
          });
          return;
        }
        this.page = res.result || res.data;
        this.model.pageNum = this.page.pageNum;
        this.model.pageSize = this.page.pageSize;
        this.matchSelected();
        this.$nextTick(()=>{
          this.$refs.table.doLayout()
        })
        
      } catch (error) {
        this.loadingListData = false;
        console.error(error);
      }
      this.loadingListData = false;
    },

    fetchData() {
      // 国际化时间字段处理
      const params = objectDateToTimestamp({...this.model}, [
        'payTimeStart',
        'payTimeEnd',
        'createTimeStart',
        'createTimeEnd',
      ])
      // 获取支付列表
      return this.$http.post(
        '/api/paycenter/outside/pay/queryPageOrder',
        params
      );
      // return this.$http.post('/outside/paymentBill/online/list', this.model)
    },

    buildParams(pageNum, pageSize) {
      return {
        ...this.model,
        pageNum,
        pageSize,
      };
    },

    buildColumns() {
      const localStorageData = this.getLocalStorageData();

      let columnStatus =
        localStorageData.columnStatus &&
        localStorageData.columnStatus[this.selectColumnState];
      columnStatus = columnStatus || [];
      // let localColumns = columnStatus
      //   .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
      //   .reduce((acc, col) => (acc[col.field] = col) && acc, {});

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let fields = tableFields;
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }
      console.log(localColumns, 'localColumns');

      this.columns = fields
        .filter(
          f =>
            f.formType !== 'attachment' &&
            f.formType !== 'separator' &&
            f.formType !== 'info' &&
            f.formType !== 'autograph'
        )
        .map(field => {
          let sortable = false;
          let minWidth = null;

          if (['date', 'datetime', 'number'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (field.fieldName === 'type') {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = 125;
          }

          if (
            field.formType === 'datetime' ||
            field.fieldName === 'updateTime' ||
            field.fieldName === 'createTime'
          ) {
            minWidth = 150;
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
            type: 'column',
          };
        })
        .map(col => {
          let show = col.show ? col.show : false;
          let { width } = col;
          let localField =
            (localColumns[col.field] && localColumns[col.field].field) || null;

          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            width =
              typeof localField.width == 'number'
                ? `${localField.width}px`
                : `${localField.width}`.indexOf('px')
                ? localField.width
                : '';
            show = localField.show ? localField.show : false;
          }

          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left';
          return col;
        });
    },

    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    },

    buildTime(value = []) {
      const [start, end] = value;
      // 交易创建时间
      this.model.createTimeStart = start;
      this.model.createTimeEnd = end;
    },

    updateCreateTime(value) {
      this.options.createTime = value;
    },

    trackEventHandler() {
      window.TDAPP.onEvent('pc：在线支付管理-更多操作事件');
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min =
          window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 20 ;
        console.log(
          window_,
          header,
          do_,
          footer,
          selection,
          'window_, header, do_, footer, selection'
        );
        console.log(min, 'min');
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    changePackUp() {
      this.packUp = !this.packUp;
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.tableKey = (Math.random() * 1000) >> 2;
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;
      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus[`${this.selectColumnState}`] =
          columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.selectColumnState}`]: columnsList,
        };
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
  },
  mounted() {
    this.buildColumns();
    this.page.pageNum = this.model.pageNum;
    this.page.pageSize = this.model.pageSize;
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', event => {
      const { action, data } = event.data;
      if (action == 'shb.frame.activatedPage') {
        that_.$nextTick(() => {
          that_.knowTableContainerHeight();
        });
      }
    });
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        that_.knowTableContainerHeight();
      }, 500);
    });
    // this.loadData();
    window.__exports__refresh = this.loadData();
  },
  components: {
    [ListSearch.name]: ListSearch,
    [TableFooter.name]: TableFooter,
  },
};
</script>

<style lang="scss" scoped>
.page-list-section .operation-bar-container .el-dropdown-btn {
  background: #fff;
}
.page-list-section .operation-bar-container .el-dropdown-btn:hover {
  color: currentColor;
}
::v-deep .el-input-group__append {
  border: none;

  .el-button {
    border-radius: 0 4px 4px 0;
    line-height: 16px;
    position: relative;
    top: 1px;
  }
}
</style>
<style lang="scss">
.bill-date {
  width: 300px;
  padding-right: 10px;

  .el-input__inner {
    height: 34px;
  }
}

.bill-bar-container {
  flex-direction: row-reverse;
}
</style>